import os
import glob
from PIL import Image, ImageFilter
import numpy as np


class ProfessionalGifMaker:
    """专业 GIF 制作工具"""

    def __init__(self):
        self.supported_formats = ('.png', '.jpg', '.jpeg', '.bmp', '.tiff', '.webp')

    def create_slideshow_gif(self, image_folder: str, output_path: str,
                             duration: int = 500, transition_frames: int = 5):
        """
        创建带过渡效果的幻灯片 GIF
        """
        images = self._load_images(image_folder)
        if not images:
            return

        # 添加过渡效果
        final_frames = []
        for i in range(len(images)):
            final_frames.append(images[i])

            # 添加过渡到下一张（如果是最后一张则过渡到第一张）
            if i < len(images) - 1:
                transition = self._create_transition(images[i], images[i + 1], transition_frames)
                final_frames.extend(transition)
            else:
                transition = self._create_transition(images[i], images[0], transition_frames)
                final_frames.extend(transition)

        # 保存 GIF
        final_frames[0].save(
            output_path,
            save_all=True,
            append_images=final_frames[1:],
            duration=duration,
            loop=0,
            optimize=True
        )
        print(f"🎉 幻灯片 GIF 创建成功: {output_path}")

    def _load_images(self, image_folder: str):
        """加载图片并统一尺寸"""
        image_files = sorted(glob.glob(os.path.join(image_folder, "*")))
        image_files = [f for f in image_files if f.lower().endswith(self.supported_formats)]

        if not image_files:
            print("⚠️ 没有找到图片文件")
            return []

        # 读取所有图片
        images = []
        for file_path in image_files:
            try:
                img = Image.open(file_path)
                images.append(img)
                print(f"✅ 加载: {os.path.basename(file_path)}")
            except Exception as e:
                print(f"❌ 加载失败 {file_path}: {e}")

        # 统一尺寸（以第一张图片为准）
        if images:
            base_size = images[0].size
            resized_images = []
            for img in images:
                if img.size != base_size:
                    img = img.resize(base_size, Image.Resampling.LANCZOS)
                resized_images.append(img)
            return resized_images

        return []

    def _create_transition(self, img1: Image.Image, img2: Image.Image, frames: int):
        """创建两张图片之间的过渡效果"""
        transition = []
        for i in range(frames):
            # 计算混合比例
            alpha = i / (frames - 1)

            # 混合图片
            blended = Image.blend(img1, img2, alpha)
            transition.append(blended)

        return transition

    def create_text_gif(self, text: str, output_path: str,
                        font_size: int = 40, duration: int = 200):
        """
        创建文字动画 GIF
        """
        from PIL import ImageDraw, ImageFont

        try:
            # 尝试加载字体
            font = ImageFont.truetype("arial.ttf", font_size)
        except:
            font = ImageFont.load_default()

        # 计算文本尺寸
        dummy_img = Image.new('RGB', (1, 1))
        draw = ImageDraw.Draw(dummy_img)
        bbox = draw.textbbox((0, 0), text, font=font)
        text_width = bbox[2] - bbox[0]
        text_height = bbox[3] - bbox[1]

        # 创建动画帧
        frames = []
        canvas_width = text_width + 100
        canvas_height = text_height + 100

        # 打字机效果
        for i in range(len(text) + 1):
            img = Image.new('RGB', (canvas_width, canvas_height), color='white')
            draw = ImageDraw.Draw(img)

            # 绘制文本
            current_text = text[:i]
            draw.text((50, 50), current_text, font=font, fill='black')

            frames.append(img)

        # 保存 GIF
        frames[0].save(
            output_path,
            save_all=True,
            append_images=frames[1:],
            duration=duration,
            loop=0,
            optimize=True
        )
        print(f"🎉 文字 GIF 创建成功: {output_path}")


# 使用示例
if __name__ == "__main__":
    gif_maker = ProfessionalGifMaker()

    # 创建幻灯片 GIF
    gif_maker.create_slideshow_gif(
        image_folder=r"C:\Users\33720\Desktop\photos",
        output_path=r"C:\Users\33720\Desktop\slideshow.gif",
        duration=1000,
        transition_frames=10
    )

    # 创建文字 GIF
    gif_maker.create_text_gif(
        text="Hello World!",
        output_path=r"C:\Users\33720\Desktop\text.gif",
        font_size=60,
        duration=100
    )